package com.siro.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siro.auth.entity.SysRole;
import com.siro.auth.entity.SysUser;
import com.siro.auth.entity.dto.RoleMenuDto;
import com.siro.auth.mapper.SysRoleMapper;
import com.siro.auth.mapper.SysUserMapper;
import com.siro.auth.service.ISysRoleService;
import com.siro.auth.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author GH
* @description 针对表【sys_role(角色信息表)】的数据库操作Service实现
* @createDate 2022-07-13 10:53:51
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public IPage<SysRole> getRolePage(Page page, SysRole sysRole) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        //角色名称
        queryWrapper.like(!ObjectUtils.isEmpty(sysRole.getRoleName()),"role_name", sysRole.getRoleName());
        //排序
        queryWrapper.orderByAsc("role_id");
        //根据用户id查询用户信息
        SysUser sysUser = sysUserMapper.selectById(SecurityUtils.getUserId());
        //TODO 如果用户不为空，且不是管理员，则只能查询自己创建的角色
        if (sysUser != null && !ObjectUtils.isEmpty(sysUser.getIsAdmin()) && sysUser.getIsAdmin() != 1) {
            queryWrapper.eq("create_by", SecurityUtils.getUsername());
        }
        IPage<SysRole> iPage = baseMapper.selectPage(page, queryWrapper);
        return iPage;
    }

    /**
     * 检查角色是否被分配出去
     *
     * @param roleId
     * @return
     */
    @Override
    public boolean checkRole(Long roleId) {
        return baseMapper.checkRole(roleId) > 0;
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @return
     */
    @Override
    public boolean deleteByRoleId(Long roleId) {
        //删除角色菜单关联表
        baseMapper.deleteMenuByRoleId(roleId);
        //删除角色表
        return baseMapper.deleteById(roleId) > 0;
    }

    /**
     * 保存权限数据
     *
     * @param roleMenuDto
     * @return
     */
    @Override
    public boolean saveRoleMenu(RoleMenuDto roleMenuDto) {
        //删除该角色对应的权限信息
        baseMapper.deleteRoleMenu(roleMenuDto.getRoleId());
        return baseMapper.saveRoleMenu(roleMenuDto.getRoleId(),roleMenuDto.getList()) > 0;
    }

    /**
     * 根据用户id查询该用户所拥有的角色id
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return baseMapper.findRoleIdByUserId(userId);
    }
}
